/*
 * kino_pwm.cpp
 *
 * Created: 17.10.2012 17:01:37
 *  Author: Heiko Metzger
 * 
 * ATtiny2313: 8MHz (Prescaler: clk/256 -> min. 60*2Hz | clk/64 -> min. 244*2Hz
 */

#define F_CPU 8000000

#include <avr/io.h>
#include <util/delay.h>

uint8_t check(uint8_t ocr, uint8_t target);

int main(void)
{
	
	// Initiieren
	DDRB = (1<<DDB2) | (1<<DDB3) | (1<<DDB4) | (1<<DDB5);			// PB 2, 3, 4, 5 als Ausgang
	
	PORTB = (1<<PB0) | (1<<PB6) | (1<<PB7);							// Pullups an PB 0, 6, 7
	
	/*PORTB |= (1<<PB2) | (1<<PB3) | (1<<PB4);						// PB 2, 3, 4 an
	PORTD |= (1<<PD5);												// PD 5 an
	_delay_ms(65);
	PORTB &= ~((1<<PB2) | (1<<PB3) | (1<<PB4));						// PB 2, 3, 4 aus
	PORTD &= ~((1<<PD5));											// PB 5 aus*/
	
	
	// Counter:
	
	TCCR0A |= (1<<WGM01) | (1<<WGM00);			// Fast PWM
	TCCR1A |= (1<<WGM12) | (1<<WGM10);			// Fast PWM, 8-Bit
	
	
	// Fuer SystemClock 128 kHz kein Prescaler => min. 500 Hz
	TCCR0B |= (1<<CS01) | (1<<CS00);							// Prescaler: clk/64 => min. 244Hz
	TCCR1B |= (1<<CS11) | (1<<CS10);
	
    while(1)
    {
		// Fuer Trafoschaltung:
		if(OCR0A == 0x00 && OCR1AL == 0x00 && OCR1BL == 0x00) {
			PORTB &= ~(1<<PB5);
		}else{
			PORTB |= (1<<PB5);
		}
        // Auf Aenderungen pruefen:
		OCR0A = check(OCR0A,  PINB & (1<<PB0));
		OCR1A = check(OCR1AL, PINB & (1<<PB6));
		OCR1B = check(OCR1BL, PINB & (1<<PB7));
		// 3,105 ms auf naechsten Zyklus warten: (0,8s fuers Dimmen wenn Schleife exakt 3,125ms dauert)
		if((OCR0A == 0x00) && (OCR1A == 0x00) && (OCR1B == 0x00)) {
			TCCR0A &= ~((1<<COM0A1) | (1<<COM0B1));			// Compare Mode: Clear on Compare Match, set at TOP
			TCCR1A &= ~((1<<COM1A1) | (1<<COM1B1));
		}else{
			TCCR0A |= (1<<COM0A1) | (1<<COM0B1);			// Compare Mode: Clear on Compare Match, set at TOP
			TCCR1A |= (1<<COM1A1) | (1<<COM1B1);
		}
		_delay_ms(3);
		_delay_us(105);
    }
}

uint8_t check(uint8_t ocr, uint8_t target) {
	// Pruefen, ob Schaltvorgang aktiv:
	if( (ocr > 0x00) & (target == 0x00) ) {
		return (ocr - 0x01);
	}
	if( (ocr < 0xFF) & (target > 0x00) ) {
		return (ocr + 0x01);
	}
	return ocr;
}
